package com.youhome.service.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youhome.common.exception.CustomException;
import com.youhome.common.json.JsonDateValueProcessor;
import com.youhome.common.response.Result;
import com.youhome.common.response.ResultCode;
import com.youhome.common.response.ResultPage;
import com.youhome.service.mapper.BCompanyMapper;
import com.youhome.service.mapper.BCounselorMapper;
import com.youhome.service.mapper.BUserMapper;
import com.youhome.service.mapper.BUserRoleMapper;
import com.youhome.service.model.*;
import com.youhome.service.service.BCounselorService;
import com.youhome.service.service.BUserService;
import com.youhome.service.service.DownloadService;
import com.youhome.service.service.UploadService;
import com.youhome.utils.DateUtils;
import com.youhome.utils.ExcelUtils;
import com.youhome.utils.ValidationUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chen365 on 2017/10/23.
 */
@Service
public class BCounselorServiceImpl implements BCounselorService {
    @Autowired
    private BUserMapper bUserMapper;
    @Autowired
    private BCompanyMapper bCompanyMapper;
    @Autowired
    private BUserRoleMapper bUserRoleMapper;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private BUserService bUserService;
    @Autowired
    private BCounselorMapper bCounselorMapper;
    @Autowired
    private DownloadService downloadService;


    @Override
    @Transactional
    public int create(Principal principal,String phone, String name, Integer sex, String email, String jobNumber, String weixin, String qq, String businessCard, String responsiblePlace, String photo) throws Exception {

        BCounselor counselor = new BCounselor();
        counselor.setUuid(UUID.randomUUID().toString());
        counselor.setName(name);
        counselor.setSex(sex);
        counselor.setEmail(email);
        counselor.setJobNumber(jobNumber);
        counselor.setWeixin(weixin);
        counselor.setQq(qq);
        counselor.setResponsiblePlace(responsiblePlace);
        counselor.setPhoto(photo);

        int success = 0;
        BUser user = new BUser();

        user.setPhone(phone);
        user.setCtime(new Date());
        user.setEnabled(true);

        //添加用户信息
        if (bUserMapper.insertSelective(user) == 1) {
            Long userId = user.getUserId();

            System.err.println(user.toString());

            BUserRole userRole = new BUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(2L); //ROLE_COUNSELOR 顾问

            //添加用户角色
            if (bUserRoleMapper.insert(userRole) == 1) {

                BUser currentUser = principal.getUser();
                BCompany company = bCompanyMapper.selectByUserId(currentUser.getUserId());
                Long companyId = company.getCompanyId();

                counselor.setUserId(userId);
                counselor.setCtime(new Date());
                counselor.setStatus(1);
                counselor.setCompanyId(companyId);

                //上传名片图片
                if (!StringUtils.isEmpty(businessCard)) {
                    //String businessCardUrl = uploadService.uploadHousePhoto(businessCard);
                    counselor.setBusinessCard(businessCard);
                }

                //上传头像
                if (!StringUtils.isEmpty(photo)) {
                    //String photoUrl = uploadService.uploadHousePhoto(photo);
                    counselor.setPhoto(photo);
                }

                //添加顾问
                if (bCounselorMapper.insertSelective(counselor) == 1) {
                    success = 1;
                }
            }
        }

        return success;
    }

    @Override
    public int update(Long counselorId, String jobNumber, String weixin, String qq, String businessCard, String responsiblePlace, String photo) throws Exception {
        BCounselor counselor = new BCounselor();
        counselor.setCounselorId(counselorId);
        counselor.setJobNumber(jobNumber);
        counselor.setWeixin(weixin);
        counselor.setQq(qq);
        counselor.setResponsiblePlace(responsiblePlace);
        counselor.setPhoto(photo);
        counselor.setUtime(new Date());
        counselor.setBusinessCard(businessCard);
        counselor.setPhoto(photo);
        int success = 0;

        //修改顾问
        return bCounselorMapper.updateByPrimaryKeySelective(counselor);

    }

    @Override
    public PageInfo<BCounselor> selectByBean(Integer page, Integer pageSize, BCounselor record) {
        if (page == null || page < 1)
            page = 1;

        if (pageSize == null || pageSize < 1)
            pageSize = 10;

        PageHelper.startPage(page, pageSize);
        List<BCounselor> list = bCounselorMapper.selectByBean(record);
        return new PageInfo<>(list);
    }

    @Override
    public List<BCounselor> selectByBean(BCounselor record) {
        List<BCounselor> list = bCounselorMapper.selectByBean(record);
        return list;
    }

    @Override
    public PageInfo<BCounselor> selectTopByCompanyID(Integer pageNumber, Integer pageSize, Long companyId) {
        BCounselor record = new BCounselor();
        record.setCompanyId(companyId);
        record.setStatus(1);
        record.setIstop(true);

        if (pageNumber == null || pageNumber < 1)
            pageNumber = 1;

        if (pageSize == null || pageSize < 1)
            pageSize = 10;

        PageHelper.startPage(pageNumber, pageSize);
        List<BCounselor> list = bCounselorMapper.selectTopByBean(record);
        return new PageInfo<>(list);
    }

    @Override
    public BCounselor selectByPrimaryKey(Long counselorId) {
        return bCounselorMapper.selectByPrimaryKey(counselorId);
    }

    @Override
    public BCounselor selectByUserId(Long userId) {
        return bCounselorMapper.selectByUserId(userId);
    }

    @Override
    public BCounselor selectByUUID(String uuid) {
        return bCounselorMapper.selectByUUID(uuid);
    }

    @Override
    public int delete(BCounselor counselor) throws Exception {
        return bCounselorMapper.updateStatusByPrimaryKey(counselor);
    }

    @Override
    public int updateIsTopByPrimaryKey(Long counselorId) {
        return bCounselorMapper.updateIsTopByPrimaryKey(counselorId);
    }

    @Override
    public int updateSortByPrimaryKey(BCounselor record) {
        return bCounselorMapper.updateSortByPrimaryKey(record);
    }

    @Override
    public int selectIsTopCountByCompanyId(Long companyId) {
        return bCounselorMapper.selectIsTopCountByCompanyId(companyId);
    }

    @Override
    public int selectCountByCompanyId(Principal principal) throws CustomException {
        Long userId = principal.getUser().getUserId();
        BCompany company = bCompanyMapper.selectByUserId(userId);
        if (company == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        return bCounselorMapper.selectIsTopCountByCompanyId(company.getCompanyId());

    }

    @Override
    public void updateSortByPrimaryKey(String uuid, Integer sort) throws CustomException {
        if (StringUtils.isEmpty(uuid) || StringUtils.isEmpty(sort)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }

        if (!ValidationUtils.isNumeric(sort.toString())) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }

        BCounselor counselor = new BCounselor();
        counselor.setUuid(uuid);
        counselor.setSort(sort);
        if (bCounselorMapper.updateSortByPrimaryKey(counselor) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public PageInfo<BCounselor> selectTopByCompanyID(String uuid, Integer pageNumber, Integer pageSize) throws CustomException {
        if (StringUtils.isEmpty(uuid)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }
        BCompany company = bCompanyMapper.selectByUUID(uuid);
        if (company == null) {
            throw new CustomException(ResultCode.INVALID_COMPANY_UUID);
        }

        BCounselor record = new BCounselor();
        record.setCompanyId(company.getCompanyId());
        record.setStatus(1);
        record.setIstop(true);

        if (pageNumber == null || pageNumber < 1)
            pageNumber = 1;

        if (pageSize == null || pageSize < 1)
            pageSize = 10;

        PageHelper.startPage(pageNumber, pageSize);
        List<BCounselor> list = bCounselorMapper.selectTopByBean(record);
        return new PageInfo<>(list);
    }

    @Override
    public void top(Long counselorId) throws CustomException {
        if (StringUtils.isEmpty(counselorId)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }
        BCounselor counselor = bCounselorMapper.selectByPrimaryKey(counselorId);
        Boolean isTop = counselor.getIstop();
        if (!isTop) {
            if (bCounselorMapper.selectIsTopCountByCompanyId(counselor.getCompanyId()) >= 9) {
                throw new CustomException(ResultCode.IS_TOP_COUNT);
            }
        }
        if (bCounselorMapper.updateIsTopByPrimaryKey(counselorId) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public void delete(Principal principal,Long counselorId) throws CustomException {
        Long userId = principal.getUser().getUserId();
        if (StringUtils.isEmpty(counselorId)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }
        BCounselor counselor = new BCounselor();
        counselor.setCounselorId(counselorId);
        BCompany company = bCompanyMapper.selectByUserId(userId);
        if (company == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        counselor.setCompanyId(company.getCompanyId());
        counselor.setStatus(0); //状态删除
        if (bCounselorMapper.updateStatusByPrimaryKey(counselor) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public void update(BCounselor counselor) throws CustomException {
        counselor.setUtime(new Date());
        if (bCounselorMapper.updateByPrimaryKeySelective(counselor) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public BCounselor selectDetails(Principal principal,Long counselorId) {
        if (StringUtils.isEmpty(counselorId)) {
            Long userId = principal.getUser().getUserId();
            return bCounselorMapper.selectByUserId(userId);
        } else {
            return bCounselorMapper.selectByPrimaryKey(counselorId);
        }
    }

    @Override
    public String export(Principal principal) throws CustomException {
        Long userId = principal.getUser().getUserId();
        BCompany company = bCompanyMapper.selectByUserId(userId);
        if (company == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        BCounselor counselor = new BCounselor();
        counselor.setCompanyId(company.getCompanyId());
        counselor.setStatus(1);

        List<BCounselor> list = selectByBean(counselor);
        if (list == null || list.size() == 0) {
            throw new CustomException(ResultCode.NO_DATA);
        }

        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());

        JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
        JSONArray jsonArray2 = new JSONArray();
        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) JSONObject.fromObject(obj);
            //性别，0：女，1：男
            jsonObject.put("sex", com.youhome.utils.StringUtils.getMarital(jsonObject.get("sex").toString()));

            //出生年月
            String ctime = jsonObject.get("ctime").toString();
            if (!StringUtils.isEmpty(ctime)) {
                jsonObject.put("ctime", DateUtils.dateFormat(ctime, "yyyy-MM-dd hh:mm:ss"));
            }
            jsonArray2.add(jsonObject);
        }


        String title = "顾问信息";
        Map<String, String> headMap = new LinkedHashMap<String, String>();

        headMap.put("jobNumber", "工号");
        headMap.put("name", "姓名");
        headMap.put("phone", "手机");
        headMap.put("responsiblePlace", "所负责地区");
        headMap.put("sex", "性别");
        headMap.put("weixin", "微信");
        headMap.put("qq", "QQ");
        headMap.put("email", "邮箱");

        //headMap.put("businessCard", "名片");
        headMap.put("ctime", "创建时间");

        String fileName = UUID.randomUUID().toString() + ".xlsx";

        String filePath = "/data/excel/" + fileName;
        try {
            OutputStream outXlsx = new FileOutputStream(filePath);

            System.out.println("正在导出xlsx....");
            Date beginTime = new Date();
            ExcelUtils.exportExcelX(title, headMap, jsonArray2, "yyyy-MM-dd hh:mm:ss", 0, outXlsx);
            System.out.println("共" + list.size() + "条数据,执行" + (new Date().getTime() - beginTime.getTime()) + "ms");
            outXlsx.close();
            uploadService.uploadExcel(filePath);
            String url = downloadService.downloadExcel("excel/" + fileName);
            if (!StringUtils.isEmpty(url)) {
                return url;
            } else {
                throw new CustomException(ResultCode.DOWNLOAD_FAIL);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResultCode.ERROR);
        }
    }

    @Override
    public List<BCounselorItem> select(Principal principal) throws CustomException {

        Long userId = principal.getUser().getUserId();
        BCompany company = bCompanyMapper.selectByUserId(userId);
        if (company == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }

        BCounselor counselor = new BCounselor();
        counselor.setCompanyId(company.getCompanyId());
        counselor.setStatus(1);

        List<BCounselor> list = bCounselorMapper.selectByBean(counselor);
        if (list.size() > 0) {
            List<BCounselorItem> counselorItems = new ArrayList<>();
            for (BCounselor item : list) {
                BCounselorItem bCounselorItem = new BCounselorItem();
                bCounselorItem.setId(item.getCounselorId());
                bCounselorItem.setName(item.getName());
                counselorItems.add(bCounselorItem);
            }
            return counselorItems;
        }
        return null;
    }

    @Override
    public PageInfo<BCounselor> select(Principal principal,Integer pageNumber, Integer pageSize, String keyword, Boolean istop) throws CustomException {
        Long userId = principal.getUser().getUserId();
        BCompany company = bCompanyMapper.selectByUserId(userId);
        if (company == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }

        BCounselor counselor = new BCounselor();

        if (!StringUtils.isEmpty(keyword)) {
            if (ValidationUtils.isNumeric(keyword) && keyword.length() >= 3) {
                counselor.setPhone(keyword);
            } else {
                counselor.setName(keyword);
            }
        }

        if (!StringUtils.isEmpty(istop)) {
            if (istop) {
                counselor.setIstop(true);
            }
        }
        counselor.setCompanyId(company.getCompanyId());
        counselor.setStatus(1);
        PageInfo<BCounselor> pageInfo = selectByBean(pageNumber, pageSize, counselor);
        return pageInfo;

    }

    @Override
    public BCounselor create(Principal principal,BCounselor map) throws CustomException {
        //判断手机号是否注册过
        if (bUserService.isExistByPhone(map.getPhone())) {
            throw new CustomException(ResultCode.REGISTERED_PHONE);
        }
        try {
            if (create(principal,map.getPhone(), map.getName(), map.getSex(), map.getEmail(), map.getJobNumber(), map.getWeixin(), map.getQq(), map.getBusinessCard(), map.getResponsiblePlace(), map.getPhoto()) == 1) {
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResultCode.FAIL);
        }
        return null;
    }

}
